package sendEmail

import (
	"fmt"
	"gopkg.in/gomail.v2"
	"huijing_mall/pkg/logger"
	"huijing_mall/variable"
	"log"
)

// 邮件发送函数
func SendEmail(to []string, code, body string) error {
	// 邮件服务器配置
	var subject string
	if body == "" {
		subject = "Please verify your device!"
		body = fmt.Sprintf("Hi! \n\nA sign in attempt requires further verification because we did not recognize your device. To complete the sign in, enter the verification code on the unrecognized device.\n\nDevice: Chrome on Windows\nVerification code: %v\n\nIf you did not attempt to sign in to your account, your password may be compromised. Visit https://www.baidu.com/ to create a new, strong password for your GitHub account.\n\nIf you'd like to automatically verify devices in the future, consider enabling two-factor authentication on your account. Visit https://gitee.com/freedom_feel/huijing_mall to learn about two-factor authentication.\n\nIf you decide to enable two-factor authentication, ensure you retain access to one or more account recovery methods. See https://gitee.com/freedom_feel/huijing_mall in the GitHub Help.\n\nThanks,\nThe GitHub Team", code)
	} else {
		subject = "Warning!!! ErrSystem !!!"
	}

	// 创建一个新的邮件
	m := gomail.NewMessage()
	m.SetHeader("From", variable.From) // 发件人 From = "wm224119@163.com"
	m.SetHeader("To", to...)           //收件人
	m.SetHeader("Subject", subject)    //邮件标题
	m.SetBody("text/plain", body)      //邮件内容

	// 创建 SMTP 客户端
	// 邮件服务器配置
	//SmtpServer   = "smtp.163.com"     // 邮件服务器地址
	//SmtpPort     = 587                // SMTP 端口（465 用于 SSL）
	//SmtpUser     = "wm224119@163.com" // SMTP 用户名
	//SmtpPassword = "WOIGZZHLZLLBAYWH" // SMTP 密码
	d := gomail.NewDialer(variable.SmtpServer, variable.SmtpPort, string(variable.SmtpUserEmail), variable.SmtpPassword)
	d.SSL = true // 确保启用 SSL/TLS 加密

	// 发送邮件
	if err := d.DialAndSend(m); err != nil {
		log.Fatal(err)
	}
	logger.Info("Email sent successfully!")
	return nil
}
